package com.adnaan.backend.service.impl;

import com.adnaan.backend.common.event.BaseEvent;
import com.adnaan.backend.common.event.EventType;
import com.adnaan.backend.common.exception.ServicesException;
import com.adnaan.backend.entity.AfterSales;
import com.adnaan.backend.entity.Order;
import com.adnaan.backend.mapper.AfterSalesMapper;
import com.adnaan.backend.service.AfterSalesService;
import com.adnaan.backend.service.OrderService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class AfterSalesServiceImpl extends ServiceImpl<AfterSalesMapper, AfterSales> implements AfterSalesService {

    @Resource
    private OrderService orderService;

    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createAfterSales(Long orderId, Long userId, Integer type, String reason, String description, String images) {
        // 检查订单是否存在
        Order order = orderService.getById(orderId);
        if (order == null) {
            throw new ServicesException("订单不存在");
        }

        // 检查是否是订单的所有者
        if (!order.getUserId().equals(userId)) {
            throw new ServicesException("不是订单的所有者");
        }

        // 检查订单状态是否允许申请售后
        if (!canApplyAfterSales(orderId)) {
            throw new ServicesException("当前订单状态不允许申请售后");
        }

        // 检查是否已经有正在处理的售后申请
        LambdaQueryWrapper<AfterSales> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AfterSales::getOrderId, orderId)
                .in(AfterSales::getStatus, 0, 1);
        if (count(wrapper) > 0) {
            throw new ServicesException("已有正在处理的售后申请");
        }

        // 创建售后申请
        AfterSales afterSales = new AfterSales();
        afterSales.setOrderId(orderId);
        afterSales.setUserId(userId);
        afterSales.setType(type);
        afterSales.setReason(reason);
        afterSales.setDescription(description);
        afterSales.setImages(images);
        afterSales.setStatus(0);

        if (save(afterSales)) {
            eventPublisher.publishEvent(new BaseEvent(this, order.getId(), order.getSupplierId(), EventType.AFTER_SALES_CREATE));
            return afterSales.getId();
        }
        throw new ServicesException("创建售后申请失败");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean handleAfterSales(Long id, Integer status, String handleNote) {
        AfterSales afterSales = getById(id);
        if (afterSales == null) {
            throw new ServicesException("售后申请不存在");
        }

        if (afterSales.getStatus() != 0 && afterSales.getStatus() != 1) {
            throw new ServicesException("该售后申请已处理完成");
        }

        afterSales.setStatus(status);
        afterSales.setHandleNote(handleNote);
        return updateById(afterSales);
    }

    @Override
    public boolean canApplyAfterSales(Long orderId) {
        Order order = orderService.getById(orderId);
        if (order == null) {
            return false;
        }
        // 只有已完成的订单可以申请售后
        return order.getStatus() == 2 || order.getStatus() == 3;
    }
} 